﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Xc.Core.Tools;

namespace ExamSelf.Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            //强制API返回JSON
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); 

            //设置log4net
            LogHelper.SetConfig();

            //设置DataBase
            //Database.SetInitializer(new CreateDatabaseIfNotExists<ExamSelfDbContext>());
        }

        protected void Application_Error(Object sender, EventArgs e)
        {
            var lastError = Server.GetLastError();
            if (lastError != null)
            {
                LogHelper.WriteLog(lastError.Message);

                if (Request != null && (new HttpRequestWrapper(Request)).IsAjaxRequest())
                {
                    Response.Clear();
                    Response.ContentType = "application/json; charset=utf-8";
                    Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(
                        new { isSuccess = false, message = lastError.Message }));
                    Response.Flush();
                    Server.ClearError();
                    return;
                }

                Response.StatusCode = 500;
                Server.ClearError();
            }
        }
    }
}
